﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace Feed_Discovery
{
    public partial class Mainform : Form
    {

        List<Feed> FeedList = new List<Feed>();
        WebBrowser Parser = new WebBrowser();

        public Mainform()
        {
            InitializeComponent();
        }

        private void Mainform_Load(object sender, EventArgs e)
        {
            String[] Args = Environment.GetCommandLineArgs();
            if (Args.Length > 1)
            {
                Uri PageToParse = new Uri(Args[1]);
                this.Text = "Disovering feeds on " + PageToParse.ToString();
                Parser.ScriptErrorsSuppressed = true;
                Parser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(FindTheFeeds);
                Parser.Navigate(PageToParse);
            }
            else
                Application.Exit();
        }

        private void FindTheFeeds(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlDocument PageToParse = ((WebBrowser)sender).Document;
            HtmlElementCollection Links = PageToParse.GetElementsByTagName("link");
            FeedList.Clear();
            listBox1.Items.Clear();
            listBox1.BeginUpdate();
            foreach (HtmlElement Link in Links)
            {
                if ((Link.GetAttribute("type") == "application/rss+xml") || (Link.GetAttribute("type") == "application/atom+xml"))
                {
                    listBox1.Items.Add(Link.GetAttribute("title"));
                    FeedList.Add(new Feed(Link.GetAttribute("title"), Link.GetAttribute("href")));
                }
            }
            listBox1.EndUpdate();
            if (listBox1.Items.Count == 0)
            {
                if (MessageBox.Show("No feeds available, use Page2RSS?", "Disovering feeds on " + PageToParse.ToString(), MessageBoxButtons.YesNo) == DialogResult.No)
                    Application.Exit();
                else
                {
                    Parser.DocumentCompleted -= FindTheFeeds;
                    Parser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GoPage2RSS);
                    Parser.Navigate(@"http://page2rss.com/api/page?url=" + PageToParse.Url.ToString().Replace("http://","").Replace("https://",""));
                }
            }
            else
            {
                this.Text = "Feeds on " + PageToParse.Url.ToString();
                listBox1.Visible = true;
            }
        }

        private void GoPage2RSS(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Process.Start((new JavaScriptSerializer().Deserialize<Dictionary<dynamic, dynamic>>(((WebBrowser)sender).DocumentText))["page"]["page"]);
            Application.Exit();
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (((ListBox)sender).SelectedIndex!=ListBox.NoMatches)
                OpenFeed(((ListBox)sender).SelectedIndex);
        }

        private void OpenFeed(int Index)
        {
            Process.Start(FeedList[Index].URL);
        }

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                int iIndex = ((ListBox)sender).IndexFromPoint(e.Location);
                if (iIndex != ListBox.NoMatches)
                {
                    ((ListBox)sender).SelectedIndex = iIndex;
                    foreach (ToolStripMenuItem Item in contextMenuStrip1.Items)
                        Item.Enabled = true;
                }
                else
                    foreach (ToolStripMenuItem Item in contextMenuStrip1.Items)
                        Item.Enabled = false;
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFeed(listBox1.SelectedIndex);
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            CopyURL(listBox1.SelectedIndex);
        }

        private void CopyURL(int Index)
        {
            Clipboard.SetText(FeedList[Index].URL);
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SubScribeWithGoogleReader(listBox1.SelectedIndex);
        }

        private void SubScribeWithGoogleReader(int Index)
        {
            Process.Start("http://fusion.google.com/add?feedurl=" + FeedList[Index].URL);
        }
    }
}
